#include "edaStruct.h"
#include "xVMRelationStruct.h"
#include <algorithm>

edaStruct::edaStruct()
{

}

void edaStruct::doInitialize()
{
	_name = "eda Test";
	_description = "This is a binary tree layout";
	_type = "ALL";
	_parameter = new ParameterCollector();
	_parameter->addParameter("1", "start", "vm", "");
	_parameter->addParameter("2", "input gate 1", "selectbox", "");
	_parameter->addParameter("3", "input gate 2", "selectbox", "");
	_parameter->addParameter("4", "output gate", "selectbox", "");
	//Add new event
	_parameter->addEvent("1","change",[this]()->void {
		string str = _parameter->getParameterValue("1");
		if (xVMRelationStruct::getInstance()->get_subVMsVarname(str).size()>0)
		{
			DIVA_VM* tVM = xVMRelationStruct::getInstance()->VMRS_searchVMByVarname(str).at(0);
			_parameter->updateDefaultValue("2",
				xVMRelationStruct::getInstance()->get_subVMsVarname(str));
			_parameter->updateDefaultValue("3",
				xVMRelationStruct::getInstance()->get_subVMsVarname(str));
			_parameter->updateDefaultValue("4",
				xVMRelationStruct::getInstance()->get_subVMsVarname(str));
		}
	});
}

void edaStruct::ImportParameter(std::string json)
{
	doLayout();
}

void edaStruct::doLayout()
{
	DIVA_VM* tmp = NULL;
	vector<DIVA_VM*> tmpVMs;
	tmpVMs = _parameter->getParameterVM("1");
	if(tmpVMs.size()!=0)
		tmp = tmpVMs.at(0);	
	else
		return;

	loc(tmp);

}

void edaStruct::loc(DIVA_VM* vm)
{
	vector<DIVA_VM*> lVMs;
	vector<DIVA_VM*> rVMs;
	_loc.push_back(vm);
	lVMs = xVMRelationStruct::getInstance()->VMRS_nextVMsByRef(vm, _parameter->getParameterValue("2"));
	rVMs = xVMRelationStruct::getInstance()->VMRS_nextVMsByRef(vm, _parameter->getParameterValue("3"));
	for (int i=0;i<lVMs.size();++i)
	{
		Ogre::Vector3 posit = vm->getPosition();
		posit.x +=100;
		posit.y +=100*(i+1);
		lVMs.at(i)->setPosition(posit);
		loc(lVMs.at(i));
	}
	for (int i=0;i<rVMs.size();++i)
	{
		Ogre::Vector3 posit = vm->getPosition();
		posit.x +=100;
		posit.y -=100*(i+1);
		rVMs.at(i)->setPosition(posit);
		loc(rVMs.at(i));
	}
}

void edaStruct::doDeinitialize()
{

}